package main

import (
	"os"
	"os/signal"
	"syscall"

	"../logger"
	"../util"
	"github.com/valyala/fasthttp"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	basepath = kingpin.Flag("path", "base path").Default(".").String()
	port     = kingpin.Flag("port", "port to listen").Default("10102").Short('p').String()
	// nmonth   = kingpin.Flag("month", "to open db within previous n month").Default("3").Short('m').String()
	DaysToKeepOpen      = kingpin.Flag("open", "to keep DBs within previous n days open").Default("15").Short('O').Int()
	IntervalToCloseDB   = kingpin.Flag("close", "to close old DBs every n minutes").Default("60").Short('C').Int()
	IntervalToReadKafka = kingpin.Flag("read", "to read messages from Kafka every n minutes").Default("5").Short('R').Int()
	MaxBuffSize         = kingpin.Flag("buffer", "max size of buffer to store kafka message").Default("1024").Short('b').Int()
)

func main() {
	kingpin.Parse()
	srv := Server{logicLayer: Logic{}}
	srv.logicLayer.Initial()
	srv.logicLayer.CloseDBEveryDay()
	// catch system call and excute Finalize()
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan)
	signal.Ignore(syscall.SIGPIPE)
	go func() {
		a := <-signalChan
		logger.Printf("Receive signal %v", a)
		srv.logicLayer.Finalize()
		os.Exit(0)
	}()
	err := fasthttp.ListenAndServe(":"+*port, srv.Handle)
	util.ErrorHandler("listen to HTTP request", err, func() error {
		return fasthttp.ListenAndServe(":"+*port, srv.Handle)
	})
}
